﻿using System;
using System.Collections.Generic;
using System.Text;
using Common;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            string pipeName = @"\\.\pipe\MyPipe";

            while (true)
            {
                Console.WriteLine("请输入信息");

                string msg = Console.ReadLine();

                if (msg == "EXIT")
                    break;

                byte[] msgBuffer = Encoding.UTF8.GetBytes(msg);

                IntPtr fileHandle;

                while (true)
                {

                    fileHandle = NamedPipeLib.CreateFile(pipeName,
                        NamedPipeLib.GENERIC_READ | NamedPipeLib.GENERIC_WRITE,
                        0, null, NamedPipeLib.OPEN_EXISTING, 0, 0);


                    if (fileHandle.ToInt32() != NamedPipeLib.INVALID_HANDLE_VALUE)
                        break;

                    if (NamedPipeLib.GetLastError() != NamedPipeLib.ERROR_PIPE_BUSY)
                    {
                        Console.WriteLine("不能打开管道");
                        return;
                    }

                    if (!NamedPipeLib.WaitNamedPipe(pipeName, 20000))
                    {
                        Console.WriteLine("不能打开管道");
                        return;
                    }
                }

                uint pipeMode = NamedPipeLib.PIPE_READMODE_MESSAGE;

                bool success = NamedPipeLib.SetNamedPipeHandleState(fileHandle, ref pipeMode, IntPtr.Zero, IntPtr.Zero);


               
                if (!success)
                {
                    Console.WriteLine("设置管道状态失败");
                    return;
                }

                uint len = (uint)msgBuffer.Length;

                byte[] numReadWritten = new byte[4];

                success = NamedPipeLib.WriteFile(fileHandle, BitConverter.GetBytes(len), 4, numReadWritten, 0);

                if (!success)
                {
                    Console.WriteLine("写入数据失败");
                    return;
                }
                else
                {
                    NamedPipeLib.WriteFile(fileHandle, msgBuffer, len, numReadWritten, 0);
                }

                NamedPipeLib.CloseHandle(fileHandle);
            }
        }
    }
}
